<template>
  <a-form ref="formRef" :model="formState" v-bind="$attrs" v-on="$listens">
    <template v-for="(item, index) in formList" :key="index">
      <a-form-item
        v-if="IsShow(item)"
        :label="item.label"
        :name="item.name"
        v-bind="item.props"
        v-on="item.events"
      >
        <a-input
          v-if="item.type === 'input'"
          v-model:value="formState[item.name]"
          v-bind="item.subProps"
        />
        <a-radio-group
          v-if="item.type === 'radio'"
          v-model:value="formState[item.name]"
          v-bind="item.subProps"
          v-on="item.subEvents"
        />
        <a-select
          v-if="item.type === 'select'"
          v-model:value="formState[item.name]"
          v-bind="item.subProps"
          v-on="item.subEvents"
        />
        <a-date-picker
          v-if="item.type === 'picker'"
          v-model:value="formState[item.name]"
          v-bind="item.subProps"
          v-on="item.subEvents"
        />
      </a-form-item>
    </template>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" html-type="submit">确认</a-button>
    </a-form-item>
  </a-form>
  <!-- <a-button type="primary" @click="handleSubmit">确认</a-button> -->
</template>

<script setup lang="ts">
const formRef = ref<FormInstance>()
const props = defineProps({
  formRef: {
    type: Object,
    default: () => {
      return null
    }
  },
  formList: {
    type: Array,
    default: () => {
      return []
    }
  },
  formState: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const emits = defineEmits(['submit'])

const IsShow = (data) => {
  // 做个二维数组分析出要相等的字段和值，存起来
  let showList = []
  if (data.show) {
    if (data.show.indexOf('&') > 0) {
      showList = data.show.split('&')
      showList = showList.map((showItem) => {
        return showItem.split('=')
      })
    } else if (data.show.indexOf('=') > 0) {
      showList = [data.show.split('=')]
    } else {
      showList = [[data.show]]
    }
    if (
      showList.every((item) => {
        if (item?.length === 2) {
          return props.formState[item[0]] == item[1]
        } else if (item?.length === 1) {
          return props.formState[item[0]]
        }
      })
    ) {
      return true
    } else {
      return false
    }
  }

  return true
}

const handleSubmit = () => {
  formRef?.value?.validate().then((err) => {
    if (!err) {
      emits('submit', formState)
    }
  })
}
</script>

<style scoped>
</style>